package com.google.code.alpaca.example.client;

import java.util.List;

import net.customware.gwt.dispatch.client.DefaultExceptionHandler;
import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.dispatch.client.standard.StandardDispatchAsync;

import com.google.code.alpaca.example.model.Message;
import com.google.code.alpaca.example.rpc.MessageAction;
import com.google.code.alpaca.example.rpc.MessageDeleteAction;
import com.google.code.alpaca.example.rpc.MessageResult;
import com.google.code.alpaca.example.rpc.VoidResult;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 
 * @author drone
 * @version 1.0
 */
public class MessageBox extends VerticalPanel {

  private final DispatchAsync dispatch = new StandardDispatchAsync(
      new DefaultExceptionHandler());

  public void update() {
    AsyncCallback<MessageResult> callback = new AsyncCallback<MessageResult>() {

      @Override
      public void onFailure(Throwable caught) {
        Window.alert("failure: " + caught.getMessage());
      }

      @Override
      public void onSuccess(MessageResult result) {
        update(result.getAllMessages());
      }

    };

    dispatch.execute(new MessageAction(), callback);

  }

  protected void update(List<Message> messages) {
    clear();

    for (Message message : messages) {
      Panel panel = new FlowPanel();
      panel.setStyleName("message");

      Label messageText = new Label(message.getText());
      messageText.setStyleName("messageText");
      panel.add(messageText);

      Button button = new Button("Delete");
      button.addStyleName("deleteButton");
      button.addClickHandler(new DeleteClickHandler(message.getId()));

      panel.add(button);

      add(panel);
    }
  }

  protected class DeleteClickHandler implements ClickHandler {

    private Long id;

    public DeleteClickHandler(Long id) {
      this.id = id;
    }

    @Override
    public void onClick(ClickEvent event) {
      AsyncCallback<VoidResult> callback = new AsyncCallback<VoidResult>() {

        @Override
        public void onFailure(Throwable caught) {
          update();
        }

        @Override
        public void onSuccess(VoidResult result) {
          update();
        }

      };

      dispatch.execute(new MessageDeleteAction(id), callback);
    }
  }
}
